package alice.exercise.leetcode.difficult;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Alice
 * @since 2023-02-06 星期一 10:09
 */
class MKAverage {
  private final int m;
  private final int k;
  private final List<Integer> list;
  private final Integer[] subArray;

  public MKAverage(int m, int k) {
    this.m = m;
    this.k = k;
    list = new ArrayList<>();
    subArray = new Integer[m];
  }

  public void addElement(int num) {

    // 0 1 2 3 4 5 6 7 8 9 10
    // 0 1 2 0 1 2 0 1 2 0 1
    //
    subArray[list.size() % m] = num;
    list.add(num);
  }

  public int calculateMKAverage() {
    int size = list.size();
    if (size < m) {
      return -1;
    }
    // m=6  size=6   =>3 4 5   k=1
    // 0 1 2 3 4 5   m=6  k=2
    // List<Integer> subList = new ArrayList<>(this.list.subList(size - m, size));
    // Collections.sort(subList);
    Arrays.sort(subArray);
    List<Integer> collect = Arrays.stream(subArray).parallel().skip(k).limit(m - 2L * k).collect(Collectors.toList());
    return collect.stream().collect(Collectors.averagingInt(Integer::intValue)).intValue();
  }
}
